package com.itheima.cs.common.dyewm;

import androidx.appcompat.app.AppCompatActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;
import com.itheima.cs.R;
import com.itheima.cs.utils.BluetoothUtil;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

public class dyewmActivity extends AppCompatActivity {

    private static final String TAG = "SunmiPrinter";
    private BluetoothSocket socket;
    private BluetoothAdapter btAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dyewm);

        btAdapter = BluetoothUtil.getBTAdapter();
        if (btAdapter == null) {
            showToast("蓝牙不可用");
            return;
        }
        Button printQRCodeButton = findViewById(R.id.printQRCodeButton);
        printQRCodeButton.setOnClickListener(v -> printQRCode("这是二维码"));

        connectPrinter();
    }

    private void connectPrinter() {
        try {
            if (socket != null) {
                socket.close();
            }
            BluetoothDevice device = BluetoothUtil.getDevice(btAdapter);
            if (device == null) {
                showToast("未找到打印机");
                return;
            }
            socket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
            socket.connect();
            showToast("打印机连接成功");
        } catch (IOException e) {
            Log.e(TAG, "连接失败", e);
            showToast("连接失败: " + e.getMessage());
            socket = null;
        }
    }

    private void printQRCode(String data) {
        try {
            if (!checkConnection()) return;
            byte[] feedBefore = {0x1B, 0x64, 0x03};
            byte[] init = {0x1B, 0x40};
            byte[] alignCenter = {0x1B, 0x61, 0x01};
            byte[] qrModel = {0x1D, 0x28, 0x6B, 0x04, 0x00, 0x31, 0x41, 0x32, 0x00};
            byte[] qrSize = {0x1D, 0x28, 0x6B, 0x03, 0x00, 0x31, 0x43, 0x08};
            byte[] qrECLevel = {0x1D, 0x28, 0x6B, 0x03, 0x00, 0x31, 0x45, 0x31};
            byte[] dataBytes = data.getBytes("GBK");
            byte[] qrDataHeader = {
                    0x1D, 0x28, 0x6B,
                    (byte) (dataBytes.length + 3), 0x00,
                    0x31, 0x50, 0x30
            };
            byte[] qrPrint = {0x1D, 0x28, 0x6B, 0x03, 0x00, 0x31, 0x51, 0x30};
            byte[] feedAfter = {0x1B, 0x64, 0x05};
            byte[] cutPaper = {0x1D, 0x56, 0x42, 0x00};

            byte[] bytes = concatBytes(
                    feedBefore,
                    init,
                    alignCenter,
                    qrModel,
                    qrSize,
                    qrECLevel,
                    qrDataHeader,
                    dataBytes,
                    qrPrint,
                    feedAfter,
                    cutPaper
            );

            sendToPrinter(bytes);
            showToast("二维码打印指令已发送");
        } catch (Exception e) {
            handleException(e);
        }
    }

    private boolean checkConnection() {
        if (socket == null || !socket.isConnected()) {
            connectPrinter();
            if (socket == null || !socket.isConnected()) {
                showToast("打印机未连接");
                return false;
            }
        }
        return true;
    }

    private void sendToPrinter(byte[] data) throws IOException {
        OutputStream os = socket.getOutputStream();
        os.write(data);
        os.flush();
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    private void handleException(Exception e) {
        Log.e(TAG, "打印错误", e);
        showToast("打印失败: " + e.getMessage());
        try {
            if (socket != null) socket.close();
        } catch (IOException ex) {
            Log.e(TAG, "关闭连接失败", ex);
        }
        socket = null;
    }

    private byte[] concatBytes(byte[]... arrays) {
        int length = 0;
        for (byte[] array : arrays) length += array.length;
        byte[] result = new byte[length];
        int pos = 0;
        for (byte[] array : arrays) {
            System.arraycopy(array, 0, result, pos, array.length);
            pos += array.length;
        }
        return result;
    }

    private void showToast(String msg) {
        runOnUiThread(() -> Toast.makeText(this, msg, Toast.LENGTH_SHORT).show());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            if (socket != null) socket.close();
        } catch (IOException e) {
            Log.e(TAG, "关闭连接失败", e);
        }
    }
}